/**
 * 画布签名
 */

//1.获取鼠标开始位置
//2.记录鼠标移动过程
//3.画布开始位置
//4.重复调用绘制位置

let moveFlag = false
export default function drawSign() {
    let cavs = document.getElementById("canvas")
    let ctx = cavs?.getContext("2d")
    pcDraw(cavs, ctx)
    Phonedraw(cavs, ctx)
}
function pcDraw(cavs, ctx) {
    cavs?.addEventListener("mousedown", (e) => {
        moveFlag = true
        ctx.beginPath()
        ctx.moveTo(e.offsetX, e.offsetY)
    })
    cavs?.addEventListener("mousemove", e => {
        if (!moveFlag) return
        drawLine(ctx, e.offsetX, e.offsetY)
        ctx.closePath()
        ctx.stroke()
        ctx.moveTo(e.offsetX, e.offsetY)
    })
    cavs?.addEventListener("mouseup", e => {
        ctx.closePath()
        ctx.stroke()
        moveFlag = false
        dataToimg(cavs, ctx)
    })
}

function Phonedraw(cavs, ctx) {
    cavs.addEventListener("touchstart", (e) => {
        moveFlag = true
        e = e.targetTouches[0]
        ctx.beginPath()
        ctx.moveTo(e.clientX - cavs.offsetLeft, e.clientY - cavs.offsetTop)
    })
    cavs?.addEventListener("touchmove", e => {
        e = e.targetTouches[0]
        if (!moveFlag) return
        drawLine(ctx, e.clientX - cavs.offsetLeft, e.clientY - cavs.offsetTop)
        ctx.closePath()
        ctx.stroke()
        ctx.moveTo(e.clientX - cavs.offsetLeft, e.clientY - cavs.offsetTop)
    })
    cavs?.addEventListener("touchend", e => {
        ctx.closePath()
        ctx.stroke()
        moveFlag = false
    })
}

//生成图片
function dataToimg(cavs, ctx) {
    console.log(cavs.toDataURL());

}
function drawLine(ctx, x, y) {
    ctx.lineTo(x, y)
}